#include "Socket.h"
#include "Tracer.h"
#include "StrUtil.h"
#include "FileUtil.h"
#include "ArgUtil.h"
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

using namespace libemb;

class MyTcpServer : public TcpServer{
public:
    void onNewConnection(std::unique_ptr<TcpSocket> client)
    {
        while(client)
        {
            char buf[64]={0};
            int rc=client->recvData(buf, sizeof(buf)-1,5000000);
            if (rc>0)
            {
                TRACE_DBG_CLASS("server recv:[%s]\n",buf); 
            }
            else if (rc<0)
            {
                TRACE_ERR_CLASS("server recv error: %d.\n",rc);
                continue;
            }
            else/* 客户端已断开连接 */
            {
                break;
            }
        }
    }   
};

int main(int argc, char* argv[])
{
	std::string argValue;
	ArgOption  argOption;
	uint16 port=5555;
	std::string ip = "0.0.0.0";
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	argOption.addOption("h", 0);	/* -h:帮助 */
	argOption.addOption("p", 1);	/* -p:指定端口 */
	argOption.addOption("i", 1);	/* -i:指定IP */
	argOption.parseArgs(argc,argv);	/* 解析参数 */

	if(argOption.getValue("h", argValue))
	{
		FilePath filePath(argv[0]);
		TRACE_YELLOW("tcp server help:\n");
		TRACE_YELLOW("%s [-h] [-p port] [-i ip]\n",CSTR(filePath.baseName()));
		TRACE_YELLOW("        -h  help\n");
		TRACE_YELLOW("        -p  server port\n");
		TRACE_YELLOW("        -i  server ip\n");
		return RC_OK;
	}

	if(argOption.getValue("p", argValue))
	{
		port = (uint16)StrUtil::stringToInt(argValue);
	}
	else
	{
		TRACE_ERR("tcp server need a port: [-p port]!\n");
		return RC_ERROR;
	}
	
	if(argOption.getValue("i", argValue))
	{
		ip = argValue;
	}

	Thread serThread;
    MyTcpServer server;
    if (!server.startServer(ip,port))
    {
    	TRACE_ERR("tcp server start error: %s:%d\n",CSTR(ip),port);
		return RC_ERROR;
	}
    if (!serThread.start(server))
    {
    	TRACE_ERR("tcp server start error.\n");
		return RC_ERROR;
	}
	Thread::msleep(2000);
	TRACE_INFO("tcp server start ok: %s:%d\n",CSTR(ip),port);
	while(1)
	{
		Thread::msleep(2000);
	}
    return 0;
}
